<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>vue响应式数据</title>
</head>
<body>
  <div id="app"></div>
  <script>
    let state = {
      count: 0
    }

    // 将state变成响应式数据
    function defineReactive(obj) {
      let active;
      for(let key in obj) {
        let value = obj[key]  // 对象对应的值
        let dep = []
        Object.defineProperty(obj, key, {
          get() {
            if(active) {
              dep.push(active)  // 依赖收集
            }
            return value
          },
          set(newValue) {
            value = newValue
            dep.forEach(active => { // 触发更新
              active()
            })
          }
        })
      }
    }
    defineReactive(state)

    const watcher = (fn) =>{
      active = fn
      fn()
      active = null
    }

    watcher(() => {
      app.innerHTML = state.count
    })

    watcher(() => {
      console.log(state.count)
    })
  </script>
</body>
</html>